import {
  Body,
  Controller,
  Get,
  Post,
  Param,
  Delete,
  HttpCode,
  HttpStatus,
  Session,
  Put,
} from '@nestjs/common';
import { UsersService } from './users.service';
import { Public } from '@/modules/auth/decorators/public.decorator';
import { User } from '@/entity/users/user.entity';

@Controller('/api/user')
export class UsersController {
  constructor(private readonly userService: UsersService) {}

  @Get('getUserList')
  async getAllUser() {
    const allUser = await this.userService.findAll();
    if (Array.isArray(allUser)) {
      return {
        code: 0,
        message: 'ok',
        data: allUser,
      };
    } else {
      return {
        code: 500,
        data: [],
        message: allUser,
      };
    }
  }

  @Public()
  @HttpCode(HttpStatus.OK)
  @Post('addUser')
  async addUser(@Body() user: any, @Session() session: Record<string, any>) {
    try {
      const sessionCaptcha = session.captcha; // 在会话中的验证码
      console.log('新增', session.captcha, user.captcha);
      if (!this.userService.verifyCaptcha(user.captcha, sessionCaptcha)) {
        return {
          code: 1000,
          data: null,
          message: '验证码输入错误',
        };
      }

      const existUser = await this.userService.findOneByName(user.username);
      if (existUser === null) {
        // 此时不存在该用户可以新增
        const data = await this.userService.addUser(user);
        if (data === undefined) {
          return {
            code: 200,
            data: [],
            message: 'ok',
          };
        } else {
          return {
            code: data.code,
            data: null,
            message: data.message.driverError.sqlMessage,
          };
        }
      } else {
        // 该用户已注册
        return {
          code: 1000,
          data: user,
          message: '该用户已注册',
        };
      }
    } catch (error) {
      console.log('error', error);
      return {
        code: 500,
        message: error,
      };
    }
  }

  @Get('getUserById/:id')
  async getUser(@Param('id') id: number) {
    const data = await this.userService.findOne(id);
    const { password, ...other } = data;
    if (data && data.id) {
      return {
        code: 200,
        message: 'ok',
        data: other,
      };
    } else {
      return {
        code: 500,
        data: {},
        message: data,
      };
    }
  }
  @Public()
  @HttpCode(HttpStatus.OK)
  @Get('findUserByName/:username')
  async findUserByName(@Param('username') username: string) {
    const res = await this.userService.findOneByName(username);
    console.log('res', res);
    if (res && res?.id) {
      return {
        code: 200,
        message: 'ok',
        data: true,
      };
    } else {
      return {
        code: 1000,
        message: '没有此用户',
        data: false,
      };
    }
  }

  @Delete('deleteUserById/:id')
  async deleteUser(@Param('id') id: number) {
    const res: undefined | any = await this.userService.remove(id);
    if (res) {
      return {
        code: 400,
        data: [],
        message: '删除成功',
      };
    } else {
      return {
        code: 0,
        message: `${id} 不存在`,
      };
    }
  }

  @Put('putUser/:id')
  async putUser(
    @Param('id') id: string | number,
    @Body() data: Partial<User>,
  ): Promise<any> {
    try {
      const upateAfter = await this.userService.upateUser(id, data);
      if (upateAfter) {
        const { password, ...otherUserData } = upateAfter;
        return {
          code: 200,
          data: otherUserData,
          message: 'ok',
        };
      } else {
        return {
          code: 1000,
          data: null,
          message: 'error',
        };
      }
    } catch (error) {
      console.log('修改后报错', error);
      return {
        code: 500,
        data: null,
        message: error,
      };
    }
  }

  @Get('findReportsHasPublishId/:publish_id/:userId')
  async findReportsHasPublishId(
    @Param('publish_id') publish_id: string,
    @Param('userId') userId: string,
  ) {
    const data = await this.userService.findReportsHasPublishId({
      publishId: publish_id,
      userId,
    });
    console.log('举报', data)
    if (data.length === 0) {
      return {
        code: 200,
        message: '该用户此前没有做此操作',
        data: data,
      };
    } else {
      return {
        code: 1000,
        data: data,
        message: '该用户此前已经做过此操作',
      };
    }
  }

  @Get('findCollectHasPublishId/:publish_id/:userId')
  async findCollectHasPublishId(
    @Param('publish_id') publish_id: string,
    @Param('userId') userId: string,
  ) {
    const data = await this.userService.findCollectsHasPublishId({
      publishId: publish_id,
      userId,
    });

    console.log('收藏', data)

    if (data.length === 0) {
      return {
        code: 200,
        message: '该用户此前没有做此操作',
        data: data,
      };
    } else {
      return {
        code: 1000,
        data: data,
        message: '该用户此前已经做过此操作',
      };
    }
  }

  @Get('findRocketHasPublishId/:publish_id/:userId')
  async findRocketHasPublishId(
    @Param('publish_id') publish_id: string,
    @Param('userId') userId: string,
  ) {
    const data = await this.userService.findRocketHasPublishId({
      publishId: publish_id,
      userId,
    });
    console.log('助力', data)
    if (data.length === 0) {
      return {
        code: 200,
        message: '该用户此前没有做此操作',
        data: data,
      };
    } else {
      return {
        code: 1000,
        data: data,
        message: '该用户此前已经做过此操作',
      };
    }
  }
}
